const router = require('express').Router()
const Student = require('../db/studentModel')

router.get('/',(req, res) => {
  Student.find()
  .then(data => res.render('index.html', {students: data })
  ,err => res.redirect('/500'))
})

router.get('/new', (req, res) => {
  res.render('insert.html')
})

router.post('/new', (req, res) => {
  new Student(req.body).save()
  .then(_ => res.redirect('/')
  ,err => res.redirect('/500'))
})

router.get('/update', (req, res) => {
  Student.findById(req.query.id)
  .then(data => res.render('update.html',{ student: data })
  ,err => res.redirect('/500'))
})

router.post('/update', (req, res) => {
  Student.findByIdAndUpdate(req.body.id, req.body)
  .then(_ => res.redirect('/')
  ,err => res.redirect('/500'))
})

router.get('/delete', (req, res) => {
  Student.findByIdAndRemove(req.query.id)
  .then(_ => res.redirect('/')
  ,err => res.redirect('/500'))
})

module.exports = router;
